package server;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;
import java.rmi.Naming;
import java.rmi.server.UnicastRemoteObject;

public class Control implements ActionListener {
	private MyJFrame jframe;
	
	private static int port = 10099;
	private static String name = "rmi:///"+Login.refName;
	
	PrintStream aPrintStream = new PrintStream(new FilteredStream(new ByteArrayOutputStream()));
	
	public Control() {
		jframe = new MyJFrame(this);
		
		System.setOut(aPrintStream);
		System.setErr(aPrintStream);
	}
	
	public void log(String s) {
		jframe.addToTextArea(s);
	}
	
	public void doStart() {
		try {
			System.setProperty("java.rmi.server.logCalls", "true");
			LoginImpl login = new LoginImpl();
			System.out.println(UnicastRemoteObject.exportObject(login, port));
			Naming.rebind(name, login);
		} catch(Exception e) {
			log(e.getMessage());
		}	
	}
	
	public void doStop() {
		try {
			Naming.unbind(name);
		} catch (Exception f) {
			System.out.println(f.getMessage());
		} 		
	}
	
	class FilteredStream extends FilterOutputStream {
		public FilteredStream(OutputStream aStream) {
			super(aStream);
		}

		public void write(byte b[]) throws IOException {
			String aString = new String(b);
			log(aString);
		}

		public void write(byte b[], int off, int len) throws IOException {
			String aString = new String(b, off, len);
			log(aString);
			FileWriter aWriter = new FileWriter("a.log", true);
			aWriter.write(aString);
			aWriter.close();
		}
	}

	public void actionPerformed(ActionEvent e) {
		if(e.getActionCommand().equals("Start")) {
			this.doStart();
			jframe.setActionText("Stop");
		} else {
			this.doStop();
			jframe.setActionText("Start");
		}
	}
}
